﻿using BarrageGameAssistant.Core.Configs;
using BarrageGameAssistant.Core.Model;
using BarrageGameAssistant.Core.Utils;

namespace BarrageGameAssistant
{
    public partial class FrmLicence : Form
    {

        /// <summary>
        /// 程序配置
        /// </summary>
        public Settings? Settings { get; set; }

        public Licence? LicInfo { get; set; }


        public FrmLicence()
        {
            InitializeComponent();
        }

        private void FrmLicence_Load(object sender, EventArgs e)
        {
            this.txtSn.Text = Settings?.Sn;
            this.txtLicence.Text = Settings?.Licence;
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(this.txtSn.Text);
            MessageBox.Show(this, $"识别码已经拷贝.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private async void btnOk_Click(object sender, EventArgs e)
        {
            if (Settings == null) return;

            if (string.IsNullOrEmpty(this.txtLicence.Text.Trim()))
            {
                MessageBox.Show(this, $"卡密码不能为空.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtLicence.Focus();
                return;
            }

            Settings.Licence = this.txtLicence.Text;

            try
            {
                ApiResult result = await LicenceUtils.GetLicence(Settings.Sn, Settings.Licence);

                if (result.code != 0)
                {
                    MessageBox.Show(this, $"{result.msg}", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.txtLicence.Focus();
                    return;
                }
                else
                {
                    if (result.data != null)
                    {
#pragma warning disable CS8604 // 引用类型参数可能为 null。
                        this.LicInfo = Licence.FromJson(result.data.ToString());
#pragma warning restore CS8604 // 引用类型参数可能为 null。

                        MessageBox.Show(this, $"{result.msg}, 授权到期时间: {this.LicInfo?.ExpTime?.ToString("yyyy-MM-dd HH:mm:ss")}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                    }
                }
            }
            catch (Exception)
            {
            }
        }
    }
}
